<template>
  <div class="clearfix">
    <a-upload
      :action="uploadAction"
      list-type="picture-card"
      :file-list="fileList"
      @preview="handlePreview"
      @change="handleChange"
      :headers="headers"
      :disabled="disabled"
      :before-upload="beforeUpload"
    >
      <div v-if="fileList.length < limit">
        <a-icon type="plus"/>
        <div class="ant-upload-text">
          {{text}}
        </div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>
<script>
import Vue from "vue";
import {ACCESS_TOKEN} from '@/store/mutation-types'

const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    let reg = new RegExp('\\\\', 'g')
    path = path.replace(reg, '/')
  }
  return path.substring(path.lastIndexOf('/') + 1)
}
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default {
  props: {
    limit: {
      type: Number,
      default: () => 1
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    size: {
      type: Number,
      default:()=>2
    },
    text:String,
    value: Array | String
  },
  data() {
    return {
      uploadAction: window._CONFIG['domianUploadURL']+'/cnUploadController/uploadOss',
      previewVisible: false,
      previewImage: '',
      fileList: [],
      headers: {},
    };
  },
  watch:{
    value(arrayList){
      let arr=[],res=[]
      if(typeof arrayList === 'string'){
        arr = [arrayList]
      }else if (arrayList!=undefined){
        arr = arrayList
      }
      if(arr[0] == undefined){
        return
      }
      arr.map((url,index)=>{
        let name = getFileName(url)
        res.push({
          uid: uidGenerator(),
          name,
          status: 'done',
          url: url,
          response: {
            status: 'history',
            result: {url},
          },
        })
      })
      this.fileList = res
    }
  },
  created() {

    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = {loginUserToken: token}
  },
  methods: {
    beforeUpload: function (file) {
      var fileType = file.type
      let uploadStatus = true
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        uploadStatus = false
      }
      var size = file.size
      if(size!=undefined && size >(this.size * 1024*1000)) {
        this.$message.warning(`文件不能超过${this.size}Mb`)
        file.status = 'error'
        uploadStatus = false
      }
      return uploadStatus
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({fileList}) {
      const arr = []

      this.fileList = fileList.map(file => {
        let json = file
        if (file.status === 'done') {
          if (file.response.success) {
            json = Object.assign({}, {
              uid: file['uid'],      // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
              name: file['name'],   // 文件名
              status: file['status'], // 状态有：uploading done error removed
              response: file['response'], // 服务端响应内容
              linkProps: file['linkProps'], // 下载链接额外的 HTML 属性
              xhr: file['xhr'], // XMLHttpRequest Header
              url: file['response'].result.url
            })
          }
        } else if (file.status === 'error') {

        } else if (file.status === 'removed') {

        }
        return json
      })
      if (this.limit === 1 && this.fileList[0].url) {
        this.$emit('change', this.fileList[0].url,)
      } else {
        this.$emit('change', this.fileList.map(file => file.url))
      }
    },
  },
  model: {
    prop: 'value',
    event: 'change'
  }
};
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
